package com.see.domain.dao;

import java.lang.reflect.Method;

import javax.jdo.PersistenceManager;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class TransactionIntercepter implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Method method = invocation.getMethod();
        Transaction annotation = method.getAnnotation(Transaction.class);
        // Make sure the intercepter was called for a transaction method
        if (annotation == null) {
            return invocation.proceed();
        }
        PersistenceManager persistenceManager = PMF.get().getPersistenceManager();
        javax.jdo.Transaction trans = persistenceManager.currentTransaction();
        try {
            trans.begin();
            // Proceed with the original method's invocation.
            Object returnObj = invocation.proceed();
            // Commit if successful.
            trans.commit();
            return returnObj;
        } catch (Throwable ex) {
            throw ex;
        } finally {
            // Rollback on error.
            if (trans.isActive()) {
                trans.rollback();
            }
            persistenceManager.close();
        }
    }

}
